//
//  WBComposeTypeView.swift
//  Weibo
//
//  Created by yinbo on 2018/4/8.
//  Copyright © 2018年 yinbo. All rights reserved.
//

import UIKit
import pop
class WBComposeTypeView: UIView {
    
    @IBAction func clickReturn(_ sender: Any) {
        scrollview.setContentOffset(CGPoint(x:0,y:0), animated: true)
        
        let margin = scrollview.bounds.width/6
        clostButtonCenterXCons.constant = 0
        returnButtonCenterXCons.constant = 0
//        UIView.animate(withDuration: 0.5) {
//            self.layoutIfNeeded()
//        }
        UIView.animate(withDuration: 0.25, animations: {
            self.layoutIfNeeded()
            self.returnButton.alpha = 0

        }) { (_) in
            self.returnButton.isHidden = true
            self.returnButton.alpha = 1
        }
        
    }
    

    @IBOutlet weak var returnButton: UIButton!
    @IBOutlet weak var returnButtonCenterXCons: NSLayoutConstraint!
    
    @IBOutlet weak var clostButtonCenterXCons: NSLayoutConstraint!
    
    var completionBlock:((_ clsName:String?)->())?
    @IBAction func closeBtn(_ sender: Any) {
        self.hideButton()
        
//        self.removeFromSuperview()

    }
    
    @IBOutlet weak var scrollview: UIScrollView!
    /*
    // Only override draw() if you perform custom drawing.
    // An empty implementation adversely affects performance during animation.
    override func draw(_ rect: CGRect) {
        // Drawing code
    }
    */
    /// 按钮数据数组
    let buttonsInfo = [["imageName": "tabbar_compose_idea", "title": "文字", "clsName": "WBComposeController"],
                               ["imageName": "tabbar_compose_photo", "title": "照片/视频"],
                               ["imageName": "tabbar_compose_weibo", "title": "长微博"],
                               ["imageName": "tabbar_compose_lbs", "title": "签到"],
                               ["imageName": "tabbar_compose_review", "title": "点评"],
                               ["imageName": "tabbar_compose_more", "title": "更多", "actionName": "clickMore"],
                               ["imageName": "tabbar_compose_friend", "title": "好友圈"],
                               ["imageName": "tabbar_compose_wbcamera", "title": "微博相机"],
                               ["imageName": "tabbar_compose_music", "title": "音乐"],
                               ["imageName": "tabbar_compose_shooting", "title": "拍摄"]
    ]
    class func compostTypeView() -> WBComposeTypeView{
        let nib = UINib(nibName: "WBComposeTypeView", bundle: nil)
        let v = nib.instantiate(withOwner: nil, options: nil)[0] as! WBComposeTypeView
        v.frame = UIScreen.main.bounds
        v.setupUI()
//        v.showCurrentView()
//        v.backgroundColor = UIColor.cz_random()
        return v
    }
    func show(completion:@escaping (_ clsName:String?)->()){
        completionBlock = completion
        guard let vc = UIApplication.shared.keyWindow?.rootViewController else{
            return
        }
        
        vc.view.addSubview(self)
        showCurrentView()
    }
//    override func awakeFromNib() {
////        setupUI()
//    }
    //MARK:监听方法
    func clickButton(button:WBComposeTypeButton){
        //1.判断当前显示的视图
        let page = Int(scrollview.contentOffset.x/scrollview.bounds.width)
        let v = scrollview.subviews[page]
        for (i,btn) in v.subviews.enumerated(){
            let anim:POPBasicAnimation = POPBasicAnimation(propertyNamed: kPOPViewScaleXY)
            let scale = (button == btn) ? 2 : 0.2
            let value = NSValue(cgPoint:CGPoint(x: scale, y: scale))
            anim.toValue = value
            anim.duration = 0.5
            btn.pop_add(anim, forKey: nil)
            let alphAmi:POPBasicAnimation = POPBasicAnimation(propertyNamed: kPOPViewAlpha)
            alphAmi.toValue = 0.2
            alphAmi.duration = 0.5
            btn.pop_add(alphAmi, forKey: nil)
            //监听最后一个
            if i==0 {
                alphAmi.completionBlock = {(_,_)->() in
                    self.completionBlock!(button.clsName)

                }
            }
        }
         print("点击按钮事件")
     }
    func clickMore(){
        scrollview.setContentOffset(CGPoint(x:scrollview.bounds.width,y:0), animated: true)
        returnButton.isHidden = false
        let margin = scrollview.bounds.width/6
        clostButtonCenterXCons.constant += margin
        returnButtonCenterXCons.constant -= margin
        UIView.animate(withDuration: 0.5) {
            self.layoutIfNeeded()
        }
        print("点击更多")
    }
    
}

extension WBComposeTypeView{
    func setupUI(){
//        let btn = WBComposeTypeButton.composeTypeButton(imageName: "tabbar_compose_music", title: "试一试")
//        btn.center = center
//        addSubview(btn)
//        btn.addTarget(self, action: #selector(clickButton), for: .touchUpInside)
        layoutIfNeeded()
        print("")
        let rect = scrollview.bounds
        let width = scrollview.bounds.width
        for i in 0..<2{
            
            let v = UIView(frame:rect.offsetBy(dx: CGFloat(i)*width, dy: 0))
            addButton(v: v, idx: i*6)
            scrollview.addSubview(v)
        }
        scrollview.contentSize = CGSize(width: 2*width , height: 0)
        scrollview.showsVerticalScrollIndicator=false
        scrollview.showsHorizontalScrollIndicator=false
        
        scrollview.bounces=false
//        scrollview.isPagingEnabled = true
        scrollview.isScrollEnabled = false
        
    }
    func addButton(v:UIView,idx:Int) {
        let count = 6
        for i in idx..<(idx+count){
            if i >= buttonsInfo.count{
                break
            }
            let dict = buttonsInfo[i]
            guard let imageName = dict["imageName"],let title = dict["title"] else{
                continue
            }
            let btn = WBComposeTypeButton.composeTypeButton(imageName: imageName, title: title)
            
            v.addSubview(btn)
            if let actionName = dict["actionName"]{
                btn.addTarget(self, action: Selector(actionName), for: .touchUpInside)
            }else{
                btn.addTarget( self, action: #selector(clickButton), for: .touchUpInside)
            }
            btn.clsName = dict["clsName"]
        }
        let btnSize = CGSize(width:100,height:100)
        let margin = (v.bounds.width-3*btnSize.width)/4
        
        for (i,btn) in v.subviews.enumerated() {
            let y = (i>2) ? (v.bounds.height-btnSize.height) : 0
            let col = i%3
            let x =    CGFloat(col+1)*margin+CGFloat(col)*btnSize.width
            if idx == 6{
                print("\(i),\(x),\(col)")
            }
            btn.frame = CGRect(x: x, y: y, width: btnSize.width, height: btnSize.height)
        }
    }
    
    
    
}
//MARK:动画方法拓展
extension WBComposeTypeView{
    //MARK:隐藏动画
    //隐藏当前视图
    func hideCurrentView(){
        let anim:POPBasicAnimation = POPBasicAnimation(propertyNamed: kPOPViewAlpha)
        anim.fromValue = 1
        anim.toValue = 0
        anim.duration = 0.5
        pop_add(anim, forKey: nil)
        anim.completionBlock = {(_,_)->() in
            self.removeFromSuperview()
        }
    }
    //隐藏动画按钮
    func hideButton(){
        let page = Int(scrollview.contentOffset.x/scrollview.bounds.width)
        let v = scrollview.subviews[page]
        for (i,btn)  in v.subviews.enumerated().reversed() {
            let anim:POPSpringAnimation = POPSpringAnimation(propertyNamed: kPOPLayerPositionY)
            anim.fromValue = btn.center.y
            anim.toValue = btn.center.y+500
            anim.beginTime = CACurrentMediaTime() + CFTimeInterval(v.subviews.count-i)*0.025
            btn.pop_add(anim, forKey: nil)
            if i==0 {
                anim.completionBlock={(_,_)->() in
                    self.hideCurrentView()
                    
                }
            }
        }
        //隐藏当前视图
        
    }
    //MARK:显示动画
    //动画显示当前视图
    func showCurrentView(){
        let anim:POPBasicAnimation = POPBasicAnimation(propertyNamed: kPOPViewAlpha)
        anim.fromValue = 0
        anim.toValue = 1
        anim.duration = 0.5
        pop_add(anim, forKey: nil)
        showButtons()
    }
    func showButtons(){
        let v = scrollview.subviews[0]
        for (i,btn) in v.subviews.enumerated(){
            //1.创建动画
            let anim = POPSpringAnimation(propertyNamed: kPOPLayerPositionY)
            anim?.fromValue = btn.center.y+400
            anim?.toValue = btn.center.y
            
            anim?.springBounciness = 8
            anim?.springSpeed = 8
            anim?.beginTime = CACurrentMediaTime() + CFTimeInterval(i)*0.025
            btn.pop_add(anim, forKey: nil)
        }
    }
}
